package com.realshare.bby.service.integral;

import com.realshare.frame.util.DateUtils;
import com.realshare.frame.util.EasyHashMap;
import com.realshare.frame.util.StringUtils;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.beetl.sql.core.engine.PageQuery;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

/**
 * 核验用户组用户
 * author leisure
 * email 15075107120@139.com
 * create 2018-10-29 下午 4:37
 * modify 2018-10-29 下午 4:37
 **/
@Service
public class VerifyUser {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SQLManager sqlManager;

    /**
     * 核验用户组用户
     * 状态：0待验证；1正常（已验证）；2验证失败；-1已删除
     */
    void verify() {
        log.info("开始核验用户组用户");
        try {
            String uSql = "update RULE_GROUP_MEMBERS set EDITOR=?,EDIT_TIME=?,STATUS=?,VERIFY_DESCRIBE=? where id=?";
            String updDate = sqlManager.selectSingle("integral.calculate.findLastPushDataTime", null, String.class);
            if (StringUtils.isNotBlank(updDate)) {
                updDate = DateUtils.formatLongDate(DateUtils.parse(updDate + "235959"));
                List<EasyHashMap> groupUsers = sqlManager.select("integral.calculate.findGroupUsers", EasyHashMap.class, updDate);
                for (EasyHashMap group : groupUsers) {
                    //处理验证sql的参数
                    String verifySql = integralDataParam(group);
                    String[] verifySqlArray = verifySql.split(";");
                    String id = group.getString("ID");
                    String groupName = group.getString("GROUP_NAME");

                    boolean verifySuccess = false;
                    String sqlStr = "";
                    SQLReady ready = null;
                    for (String s : verifySqlArray) {
                        sqlStr = s;
                        PageQuery<EasyHashMap> pageQuery = new PageQuery<EasyHashMap>(1, 1);
                        pageQuery = sqlManager.execute(new SQLReady(s), EasyHashMap.class, pageQuery);
                        if (pageQuery.getList().size() > 0) {
                            //返回数据，核验成功
                            ready = new SQLReady(uSql, "system", DateUtils.getNowDateTime(), "1", "核验成功", id);
                            verifySuccess = true;
                            break;
                        }
                    }
                    if (!verifySuccess) {
                        String errorMsg = "根据核验sql未查询到记录，【" + groupName + "】【" + sqlStr + "】";
                        log.error(errorMsg);
                        ready = new SQLReady(uSql, "system", DateUtils.getNowDateTime(), "2", errorMsg, id);
                    }
                    sqlManager.executeUpdate(ready);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("核验用户组出错，错误信息为：" + e.getMessage());
        }
        log.info("结束核验用户组用户");
    }

    /**
     * 处理验证sql的参数
     *
     * @param group 需要处理的集合
     * @return 处理之后的sql
     */
    private String integralDataParam(EasyHashMap group) throws SQLException {
        String verifySql = group.getString("VERIFY_RULES");
        verifySql = verifySql.replaceAll("\\$\\{用户标识号}", group.getString("ID_NO"));
        //替换当前系统时间
        verifySql = verifySql.replaceAll("\\$\\{当前系统时间}", DateUtils.format(new Date(), "yyyyMMddHHmmss"));
        return verifySql;
    }

}
